import {app as appStyle} from '@/styles/scene.less'
import wall from '@/assets/wall.png'
import tank from '@/assets/tank.png'
import wallsData from '@/assets/map.json'
import AiTank from '@/tools/aiTank.js'

export default function () {
  const app = document.querySelector('#app')
  app.className = appStyle
  const scene = document.createElement('canvas')
  scene.width = 800
  scene.height = 800
  scene.style.background = '#000'
  app.appendChild(scene)

  const ctx = scene.getContext('2d');
  const img = new Image();
  img.src = wall;

  // 创建一个函数来绘制所有墙壁
  function drawWalls() {
    for (let i = 0; i < wallsData.length; i++) {
      const wall = wallsData[i];
      ctx.drawImage(img, wall[0], wall[1], 50, 50);
    }
  }

  img.onload = function () {
    drawWalls();
  };

  // 生成敌方坦克
  const img2 = new Image();
  img2.src = tank;
  img2.onload = function () {
    const aiTank = new AiTank(img2)
    aiTank.position = {
      x: 50,
      y: 0,
    }
    ctx.drawImage(img2, aiTank.position.x, aiTank.position.y, 50, 50);

    const aiTank2 = new AiTank(img2)
    aiTank2.position = {
      x: 200,
      y: 0,
    }
    ctx.drawImage(img2, aiTank2.position.x, aiTank2.position.y, 50, 50);

    const aiTank3 = new AiTank(img2)
    aiTank3.position = {
      x: 400,
      y: 0,
    }
    ctx.drawImage(img2, aiTank3.position.x, aiTank3.position.y, 50, 50);
    setInterval(() => {
      tankMove(aiTank)
      tankMove(aiTank2)
      tankMove(aiTank3)
    }, 10)
  };

  function tankMove(aiTank) {
    // 记录旧位置
    const oldX = aiTank.position.x;
    const oldY = aiTank.position.y;

    // 清除坦克旧位置
    ctx.clearRect(oldX, oldY, 50, 50);
    // 重新绘制被清除区域的墙壁
    for (let wall of wallsData) {
      if (wall[0] < oldX + 50 && wall[0] + 50 > oldX &&
          wall[1] < oldY + 50 && wall[1] + 50 > oldY) {
        ctx.drawImage(img, wall[0], wall[1], 50, 50);
      }
    }

    // 移动坦克
    aiTank.move();

    // 保存当前画布状态
    ctx.save();

    // 将坐标原点移到坦克中心
    ctx.translate(aiTank.position.x + 25, aiTank.position.y + 25);

    // 根据方向旋转
    const rotations = {
      0: Math.PI,
      1: -Math.PI / 2,
      2: 0,
      3: Math.PI / 2
    };
    ctx.rotate(rotations[aiTank.aim]);

    // 绘制坦克（因为坐标原点已移动到中心，所以要偏移回去）
    ctx.drawImage(img2, -25, -25, 50, 50);

    // 恢复画布状态
    ctx.restore();
  }
}
